package client;

import java.awt.Point;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import nanoxml.XMLElement;
import utils.ITransmittable;

import commands.Commands;

/**
 * The previous {@link Move}s of the pieces on the board in a certain game. 
 */
public class History implements ITransmittable
{
	private List<Move> listMoves = null;
	private List<String> listMovesStrings = null;
	
	
	public History()
	{
		listMoves = new LinkedList<Move>();
		listMovesStrings = new LinkedList<String>();
	}
	
	public History(History historyToClone)
	{
		this();
		
		for (Move currMoveToAdd : historyToClone.listMoves)
		{
			addMove(new Move(currMoveToAdd));
		}
	}
	
	@SuppressWarnings("unchecked")
	public History (XMLElement message) {
		this();
		
		// Go over all the moves in the history, build them according to the XML and add to the list
		Enumeration<XMLElement> enumerationChildren = message.enumerateChildren();
		while (enumerationChildren.hasMoreElements())
		{
			XMLElement childElement = enumerationChildren.nextElement();
			Move move = new Move(childElement);
			listMoves.add(move);
			listMovesStrings.add(getMoveName(move));
		}
	}

	private String getMoveName(Move move)
	{
		String moveName = move.getPlayerColorName() + " player : From " + getCellName(move.getFrom()) + " to " + getCellName(move.getTo());
		return moveName;
	}
	
	/**
	 * Create a name for each cell. The column gets a letter, starting from "a", and the row gets a number, starting from 1.
	 * For example : the cell on the 2nd column, 4th row will get the name "(b, 4)"
	 * 
	 * @param pointCell - The cell whose name is to be created.
	 * 
	 * @return The name of the given cell.
	 */
	private String getCellName(Point pointCell)
	{
		int x = pointCell.x;
		int y = pointCell.y;
		
		y = Board.NUM_OF_ROWS - y;
		
		String letter = Board.BORDER_LETTERS[x];
		int number = y;
		
		return "(" + letter + ", " + number + ")";
	}
	
	public void addMove(Move moveToAdd)
	{
		listMoves.add(0, moveToAdd);
		listMovesStrings.add(0, getMoveName(moveToAdd));
	}

	@Override
	public XMLElement toXML()
	{
		XMLElement message = new XMLElement ();
		
		message.setName(Commands.HISTORY);
		
		// Add all the moves
		for (Move currMove : listMoves)
		{
			message.addChild(currMove.toXML());
		}
		
		return message;
	}
	
	public List<String> getMovesStrings()
	{
		return listMovesStrings;
	}
}
